package com.github.niefy.modules.oss.cloud;


import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 本地文件存储 -go-fastdfs
 * @author: smalljop
 * @create:
 */
@Slf4j
public class GoFastdfsStorageService extends AbstractCloudStorageService {

    public GoFastdfsStorageService(CloudStorageConfig config) {
        this.config = config;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            InputStreamResource isr = new InputStreamResource(inputStream, path);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", path);
            params.put("output", "json");
            String resp = HttpUtil.post(config.getGofastdfsDomain() + "/group1/upload", params);
            log.info("resp: {}", resp);
            JSONObject obj = JSONObject.parseObject(resp);
            path = obj.get("path").toString();
            return config.getGofastdfsDomain() + path;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            InputStream inputStream = new ByteArrayInputStream(data);
            InputStreamResource isr = new InputStreamResource(inputStream, path);
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("path", path);
            params.put("output", "json");
            String resp = HttpUtil.post(config.getGofastdfsDomain() + "/group1/upload", params);
            log.info("resp: {}", resp);
            JSONObject obj = JSONObject.parseObject(resp);
            path = obj.get("path").toString();
            return config.getGofastdfsDomain() + path;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getGofastdfsPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getGofastdfsPrefix(), suffix));
    }
}
